package auth_svc

import (
	"admin-system/internal/dao"
	"admin-system/internal/models/auth_model"
	"github.com/gin-gonic/gin"
	"log/slog"
)

type RoleService struct {
	dao *dao.DaoProvider
}

func NewRoleService(dao *dao.DaoProvider) *RoleService {
	return &RoleService{
		dao: dao,
	}
}

// GetUserAllRoles
func (r *RoleService) GetUserAllRoles(c *gin.Context) (roles *auth_model.Role, err error) {
	roles, err = r.dao.RoleDao.GetUserAllRoles(c)
	if err != nil {
		return nil, err
	}
	return roles, nil
}

// AssignMenuToRole 给角色分配菜单
// 角色分配菜单
func (r *RoleService) AssignMenuToRole(c *gin.Context, roleId int64, menuIds []int64) error {
	// 判断角色是否存在
	_, err := r.dao.RoleDao.GetRoleByID(c, roleId)
	if err != nil {
		slog.Any("角色不存在", err)
		return err
	}
	//  查询角色菜单
	roleMenu, err := r.dao.RoleMenuDao.GetRoleMenus(c, roleId)
	if err != nil {
		return err
	}
	// 参数中的菜单ID转为map
	newMenuIdMap := make(map[int64]struct{})
	for _, newId := range menuIds {
		newMenuIdMap[newId] = struct{}{}
	}

	oldMenuIdMap := make(map[int64]struct{})
	for _, oldId := range roleMenu {
		oldMenuIdMap[oldId.MenuID] = struct{}{}
	}
	// 查询需要新增的菜单
	var addMenuIds []int64
	// 从参数传入的菜单中查找是否有新增的菜单
	for newId := range newMenuIdMap {
		if _, ok := oldMenuIdMap[newId]; !ok {
			addMenuIds = append(addMenuIds, newId)
		}
	}

	// 查询需要删除的菜单
	var deleteMenuIds []int64
	for oldId := range oldMenuIdMap {
		if _, ok := newMenuIdMap[oldId]; !ok {
			deleteMenuIds = append(deleteMenuIds, oldId)
		}
	}

	// 执行变更用户菜单权限操作

	return nil
}
